
import store from '@/store'
import OperateLogApi from '@/api/system/OperateLogApi.js'
const modulesFiles = require.context('./url', true, /\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const value = modulesFiles(modulePath)
  return modules.concat(value.default)
}, [])

/**
 * 处理系统日志
 *
 * @param url
 *            接口地址
 * @param params
 *            请求参数
 * @param result
 *            请求结果
 * @return null
 *
 */
const spliceUrl = url => {
  /**
   * 将形如：http://192.168.55.117/services/afs/afsInfo/page?page=1&size=20
   * 截取为：/afsInfo/page这种形式
   */
  let path = ''
  let api = ''
  if (url.indexOf('?') === -1) {
    path = url.slice(0)
  } else {
    path = url.slice(0, url.indexOf('?'))
  }
  const pathArr = path.split('/').reverse()
  if (pathArr.length > 2) {
    api = '/' + pathArr[1] + '/' + pathArr[0]
  } else {
    api = ''
  }
  return api
}
const addOperateLog = (response, result = true) => {
  try {
    const url = response.config.url
    modules.some(ele => {
      if (spliceUrl(url) === ele.api) {
        let reqData = {} // 发送给后端的数据
        if (response.config.data) {
          reqData = JSON.parse(response.config.data)
        }
        if (response.config.params) {
          reqData = { ...reqData, ...response.config.params }
        }
        let resData = {} // // 后端返回的数据
        if (response.data) resData = response.data.data
        const content = ele.formatter(reqData, resData, response.config) // 返回组装好的content
        content && OperateLogApi.addLog(
          {
            ...ele,
            realName: store.getters.getUser && store.getters.getUser.realName || '',
            operateResult: result,
            content: content
          }
        )
        return true
      }
    })
  } catch (error) {
    console.error('操作日志报错', error)
  }
}
export default addOperateLog
